﻿using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;

namespace Extension {
  /// <summary>
  /// 解密
  /// </summary>
  public static class Decryption {

    /// <summary>
    ///   使用RSA解密
    /// </summary>
    /// <param name="cipherData">密文</param>
    /// <param name="key">密钥</param>
    /// <returns>明文</returns>
    public static string DecryptRSA(string cipherData, string key) {
      if(cipherData == null) return null;
      // 密匙容器的名称，保持加密解密一致才能解密成功
      var param = new CspParameters { KeyContainerName = key };

      using(var rsa = new RSACryptoServiceProvider(param)) {
        var encryptdata = Convert.FromBase64String(cipherData);
        var decryptdata = rsa.Decrypt(encryptdata, false);

        return Encoding.UTF8.GetString(decryptdata);
      }
    }
    public static string Decode(string str) => str.Aggregate("", (current, t) => current + (char)(t - 10 + 1 * 2));

    /// <summary>
    /// 加密用户密码
    /// </summary>
    /// <param name="cipherData">密码</param>
    /// <param name="codeLength">加密位数</param>
    /// <returns>加密密码</returns>
    public static string md5(string cipherData, int codeLength) {
      if(!string.IsNullOrEmpty(cipherData)) {
        // 16位MD5加密（取32位加密的9~25字符）  
        if(codeLength == 16) {
          return FormsAuthentication.HashPasswordForStoringInConfigFile(cipherData, "MD5").ToLower().Substring(8, 16);
        }

        // 32位加密
        if(codeLength == 32) {
          return FormsAuthentication.HashPasswordForStoringInConfigFile(cipherData, "MD5").ToLower();
        }
      }
      return string.Empty;
    }
  }
}
